<?
/**
 * Usage:
 * new Paging(string HREF BEFORE, string HREF AFTER, int CURRENT PAGE, int MAX PAGE[, 
 * Array('left' => int, 'center' => [3,5,7,...], 'right' => int)]
 * );
 * @author dzver <dzver@abv.bg>
 */

class Paging {
	protected $sep = ' ... ';
	protected $lblNext = 'Следваща »';
	protected $lblPrev = '« Предишна';

	public function __construct($linkBefore, $linkAfter, $page, $maxpage, 
		$size = Array('left'=>5, 'center'=>3, 'right'=>3) ) 
	{
		$this->linkBefore = $linkBefore;
		$this->linkAfter = $linkAfter;
		$this->page = $page;
		$this->maxpage = $maxpage;
		$this->size = $size;

		$this->Run();
	}

	protected function PageLink($link, $selected, $text){
		?> <a href="<?=$link;?>" class="Page<?
		if ($selected) echo " selectedPage";
		?>"><?=$text;?></a><?
	}

	protected function MulPages($start, $end) {
		for ($i = $start; $i <= $end && $i <= $this->maxpage; $i++) {
			$this->PageLink($this->linkBefore . $i . $this->linkAfter, $i == $this->page, $i);
		}
	}

	protected function Run() {
		$separator = false;
		$halfsize = floor($this->size['center']/2);

		if ($this->page > 1)
			$this->PageLink($this->linkBefore . ($this->page-1) . $this->linkAfter, false, $this->lblPrev);

		if ($this->maxpage <= $this->size['left'] + $this->size['right']) {
			$this->MulPages(1, $this->maxpage);
		}
		else {
			$this->MulPages(1, $lastmax = $this->size['left']);

			if ($this->page > $this->size['left'] + $halfsize + 1) {
				echo $this->sep;
				$separator = true;
			}

			if ($this->page > $this->size['left'] - $halfsize && $this->page < $this->maxpage - $this->size['right'] + $halfsize) {
				$this->MulPages(
					($this->page - $halfsize <= $lastmax) ? 
						$lastmax + 1 : $this->page - $halfsize, 
					$lastmax = ($this->page + $halfsize >= $this->maxpage - $this->size['right']) ?
						$this->maxpage - $this->size['right'] : $this->page + $halfsize
				);
				$separator = false;
			}

			if (!$separator && $lastmax < $this->maxpage - $this->size['right']) {
				echo $this->sep;
			}
			
			$this->MulPages($this->maxpage - $this->size['right'] + 1, $this->maxpage);
		}

		if ($this->page < $this->maxpage) 
			$this->PageLink($this->linkBefore . ($this->page + 1) . $this->linkAfter, false, $this->lblNext);
	}
}
